package api

import (
	"demo/api/dto/request"
	"demo/api/dto/response"
	"demo/application/service"
	"demo/infra/middleware/auth"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

type AuthHandler struct {
	userService *service.UserService
}

func NewAuthHandler(service *service.UserService) *AuthHandler {
	return &AuthHandler{userService: service}
}

// Login 登录处理
func (h *AuthHandler) Login(c *gin.Context) {
	var req request.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
	}
	loginIp := c.ClientIP()
	user, err := h.userService.Login(c, req.Username, req.Password, loginIp)
	if err != nil {
		c.JSON(http.StatusOK, response.Error("B0001", "登录失败："+err.Error()))
		return
	}
	if err := auth.SetSession(c.Writer, c.Request, user); err != nil {
		log.Fatalf("会话创建失败," + err.Error())
		c.JSON(http.StatusOK, response.Error("B0001", "会话创建失败"))
		return
	}
	// 返回成功信息
	c.JSON(http.StatusOK, response.Success("登录成功"))

}

// LoginPage 登录页面
func (h *AuthHandler) LoginPage(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{
		"Error":    "",
		"Redirect": c.Query("redirect"),
		"PageType": "login",
	})
}

// Register 注册处理
func (h *AuthHandler) Register(c *gin.Context) {
	var req request.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
		return
	}
	if err := h.userService.Register(c, req.Username, req.Password); err != nil {
		c.JSON(http.StatusOK, response.Error("B0001", "注册失败："+err.Error()))
		return
	}
	// 返回成功信息
	c.JSON(http.StatusOK, response.Success("注册成功"))
}

// RegisterPage 注册页面
func (h *AuthHandler) RegisterPage(c *gin.Context) {
	c.HTML(http.StatusOK, "register.html", gin.H{"PageType": "register"})
}

// Logout 登出处理
func (h *AuthHandler) Logout(c *gin.Context) {
	_ = auth.ClearSession(c.Writer, c.Request)
	c.Redirect(http.StatusSeeOther, "/auth/loginPage")
}

// Profile 用户信息
func (h *AuthHandler) Profile(c *gin.Context) {
	user, err := auth.GetCurrentContextUser(c)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"id":       user.ID,
		"username": user.Username,
	})
}
